-- ==== BEGIN LICENSE BLOCK ====
-- storyboard-addon - Copyright (C) Arnaud Charnoz, 2006-2010.
-- Distributed under the terms of the GNU Lesser General Public License (LGPL) as
-- published by the Free Software Foundation.
-- ===== END LICENSE BLOCK ====
 
LocationDB = {};
 
LocationDB.__index = LocationDB;
 
function LocationDB:new()
    
    local self = {};
    setmetatable(self, LocationDB);
     
    self.key  = "Unknow";
    self.db = {};
  
    return self;
end

--[ Method to set db to locationDB object ]-- 
function LocationDB:setDb( newDb )
     self.db = newDb;
end

--[ Method to get db to locationDB object ]-- 
function LocationDB:getDb()
     return self.db;
end

--[ Method to add a location in db ]-- 
function LocationDB:addLocation( location )
    -- table.insert( self.db, location:getKey(), location );
    self.db[ location:getKey() ] = location;
    --table.insert( self.db, location );
    --SBMessageManager:debugMessage("Nb of location in DB = "..# self.db);
    --for k,v in pairs(self.db) do print(k) end
    
end

-------------------------------------------------------------------------------

function LocationDB:removeLocation( key )

    self.db[ key ] = nil;
    
end

-------------------------------------------------------------------------------

--[ Method to get a location from db ]-- 
function LocationDB:getLocation( key )
    
    for k,v in pairs(self.db) do
        if ( k == key )
        then
            return v;
        end
    end
  
    return nil;
end

--[ Method to test if a key is present in db ]-- 
function LocationDB:hasKey( key )
    
    for k,v in pairs(self.db) do
        if ( k == key )
        then
            return true;
        end
    end
  
    return false;
end

--[ Test if player is present in a location and return the key if true else return nil ]-- 
function LocationDB:hasLocationWherePlayerIs()
    
    SBMessageManager:debugMessage("Nb of location in DB = "..# self.db);
    
    for k,v in pairs(self.db) do
        if ( v:playerIsPresent() )
        then
            return k;
        end
    end
  
    return nil;
end


function LocationDB:exportToTable()
    
    local dataTable = {} ;
    
    for k,v in pairs(self.db) do
        table.insert( dataTable, v:exportToTable() );
    end

    return dataTable;
    
end


function LocationDB:importFromTable( dataTable )
    
    self.db = {};
   
   
    for index,v in ipairs( dataTable ) do
        local newLocation = Location:new();
        newLocation:importFromTable( v );
        self:addLocation( newLocation );
    end

end
